<?php

require_once(OC::$SERVERROOT."/apps/resumes/lib/resume.php"); 

/**
 * Upload model extends from PResumesModelResume 
 */
class PResumesModelUpload extends PResumesModelResume
{
   public function saveAddResume(){
      if(!PSession::checkToken('post')) {
         $this->setError('登录已失效，请重新登录');
         return false;
      }
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();
      $db->stayOnMaster();
      $job_id=JRequest::getInt('job_id',0);
      $selected_job_id = $job_id;
      //$origin_job_id:edit a rerume,record job_id 
      $origin_job_id = JRequest::getInt('oldjobid',0);
      $jobseekerid=JRequest::getInt('jobseekerid',0);
      $type=empty($jobseekerid) ? 'add' : 'edit';
      //$autoinvite = JRequest::getInt('autoinvite', 0);
      $post = JRequest::get("post");
      if(empty($post['name'])||empty($post['phone'])||empty($post['sex'])){
         $db->leaveOnMaster();
         $this->setError('姓名，性别或手机可能为空，请重新检查');
         return false;
      }
	  
      if(!empty($post['email']) && !JMailHelper::isEmailAddress($post['email'])) {
         $db->leaveOnMaster();
         $this->setError('请输入正确格式的电子邮件，请重新检查');
         return false;
      }

      if(!JobHelper::isMobilePhone(JRequest::getString('phone',''))){
         $db->leaveOnMaster();
         $this->setError('请输入11位手机号，请重新检查');
         return false;
      }
	  
      //check name valid
      if(preg_match("/[`~!@#$%^&*()+={}'\",.:;\[\]<>\/?]/", $post["name"])) {
			$db->leaveOnMaster();
      	$this->setError("姓名不能含有非法字符，请重新检查");
      	return false;
      }
      
      //check name length
      if(JString::strlen($post["name"]) > 20) {
      	$db->leaveOnMaster();
      	$this->setError("姓名为20个以内字符，请重新检查");
      	return false;
      }
      
      //if new uploaded resume selects nojob,check if have nojob' id in table jobs_job of current company
      if(empty($job_id)){
         $job_id=$this->getCompanyUploadJobId();
      }else {
         $query = "SELECT COUNT(*) FROM #__jobs_job WHERE id=".intval($job_id) . " AND system=0 AND employer_id=" . $user->id;
         $db->setQuery($db->useMaster($query));
         if(!$db->loadResult() > 0) {
            $db->leaveOnMaster();
            $this->setError("请选择正确的职位");
            return false;
         }
      }

      // support fake email address if it's not provided 
      if(empty($post['email'])) 
         $post['email'] = $post['phone'].'@'.$user->id; 

      //edit resume,if this resume has existed,cannot edit
      $jobseekerinfo=null;
      if(!empty($jobseekerid)){ 
         $jobseekerinfo=$this->getResumeJobDetail($jobseekerid);
         //check current resume is exist
         if(empty($jobseekerinfo)){
            $db->leaveOnMaster();
            $this->setError('该简历不存在');
            return false;
         }
         //check current resume is aready exist
         if($this->checkResumeExists($post['email'],$job_id,null, $jobseekerid)){
            $db->leaveOnMaster();
            $this->setError('该简历已存在');
            return false;
         }
      }else{
         //check email,name,job,check current uploading resume if has a same resume
         if(!empty($selected_job_id)){
            if($this->checkResumeExists($post['email'], $selected_job_id, 'upload')){
               $db->leaveOnMaster();
               $this->setError('该简历已存在');
               return false;
            }
            
         }
      }
      
      /*if($autoinvite){
         $query = "SELECT COUNT(*) FROM *PREFIX*hr_company_interview as hci 
                    LEFT JOIN #__jobs_job AS jj ON jj.id = hci.job_id 
                    WHERE jj.employer_id=" . intval($user->id) ." AND hci.job_id=".intval($job_id);
         $db->setQuery(PUtil::replaceOCPrefix($query));
         $hasrule = $db->loadResult();        
         if(!$hasrule) {
            $db->leaveOnMaster();
            $this->setError('uninvite');
            return false;
         }
      }*/
      
      if(!PResumesHelper::checkResumeUploadPermission($jobseekerinfo, $job_id)) {
         $db->leaveOnMaster();
         $this->setError('您无权访问该资源');
         return false;
      }
     
      // check this resume storage if jobseekerid is given or by hash key 
      $storehash = PStorage::getResumeStorageHash($post); 
      $resumeversion = PStorage::getResumeVersion($post); 
      if(!$storehash) {
         $db->leaveOnMaster();
         // this should not happen 
         $this->setError('电子邮件和手机可能为空，请重新检查');
         return false;
      }

      // get resume storage. We don't care about whether it's uploading new or editing, any changes must be matched this new storehash 
      $uresume = PStorage::getResumeStorageInfoByHashKey($storehash); 

      // update jobseeker resume record. if the email is fake email, we don't use it. When multiple companies upload
      // same resumes, the last one holds. 
      // When this user resume has user_updated true, we will not do update again as this user has updated his resume 
      if(!$uresume || !$uresume->user_updated) {

         // to avoid data overwritten, we don't overwrite any other values if duplicate key is found. 
         $query = 'INSERT INTO *PREFIX*resumes (id, source, name,email,sex,phone,hashkey, latest_version, date_added, date_updated) VALUES ( ' . 
                   (empty($uresume->id) ? 'NULL' : $uresume->id) . ', ' . 
                   $db->quote('upload') . ',' . 
                   $db->quote($post['name']) . ',' . 
                   (isFakeEmail($post['email']) ? '""' : $db->quote($post['email'])) . ',' . 
                   $db->quote($post['sex']) . ',' . 
                   $db->quote($post['phone']) . ',' . 
                   $db->quote($storehash) . ',' . 
                   $db->quote($resumeversion) . ',' . 
                   'UTC_TIMESTAMP(), ' . 
                   'UTC_TIMESTAMP())   
                   ON DUPLICATE KEY UPDATE
                   source=IF(locate("upload",source),source,concat_ws(",",source,"upload")),
                   id=LAST_INSERT_ID(id)';

         $db->setQuery(PUtil::replaceOCPrefix($query));
         if(!$db->execute()) {
            $db->leaveOnMaster();
            $this->setError('网络异常，请重试！');
            return false;
         }

         $query = 'SELECT LAST_INSERT_ID()';
         $db->setQuery($db->useLastConnection($query));
         $resume_id=$db->loadResult();
         CacheHelper::triggerRemove($user->id, array('*PREFIX*resumes-'.$resume_id));
      }
      else 
         $resume_id = $uresume->id; 


      // if the jobseeker has linked to existing resume, we need to move it to correct location 
      if($jobseekerid) {
         $old_uresume = PStorage::getResumeStorageInfoById($jobseekerinfo->resume_id);
         if($old_uresume->hashkey != $storehash) {
            // hashkey is changed, we need to move the storage to another location to match the hashkey 
            PStorage::copyResumeStoragePath($old_uresume, $storehash); 

            // if the old_uresume has one reference (which is this jobseeker), we can remove it safely 
            if($old_uresume->numjobseekers <= 1) {
               PStorage::removeResumeStoragePath($old_uresume); 
               PStorage::deleteResumeStorageInfo($old_uresume->id);
            }
         }
      
      }

      // the resume version uses company id to indicate where it belongs. By doing so, we can find whether a uploaded resume is latest or not 
      $sql='('. (intval($jobseekerid) ? intval($jobseekerid) : 'NULL') . ',
             '.$resume_id.',
             '.intval($resumeversion).',
             '.$user->id.',
             '.$job_id.',
             "upload",
             '.$db->quote($post['name']).',
             '.$db->quote($post['email']).',
             '.$db->quote($post['sex']).',
             '.$db->quote($post['phone']).',           
             UTC_TIMESTAMP(),
             UTC_TIMESTAMP())';    
      $query = 'INSERT INTO *PREFIX*hr_jobseeker (id, resume_id, version, company_id, job_id, source, name,email,sex,phone,date_added,date_updated)
                values '.$sql.' ON DUPLICATE KEY UPDATE
                resume_id = values(resume_id), 
                version = values(version), 
                job_id=values(job_id),
                source=IF(locate("upload",source),source,concat_ws(",",source,"upload")),
                name=values(name),
                email=values(email),
                sex=values(sex),
                phone=values(phone),
                date_added=values(date_added),
                date_updated=values(date_updated),
                id=LAST_INSERT_ID(id)';

      $db->setQuery(PUtil::replaceOCPrefix($query));
      if(!$db->execute()) {
         $db->leaveOnMaster();
         $this->setError('网络异常，请重试！');
         return false;
      }
      $query = 'SELECT LAST_INSERT_ID()';
      $db->setQuery($db->useLastConnection($query));
      $jobseeker_id=$db->loadResult();
      //if auto invite and job_id's system is not equal 1
      /*if($autoinvite){
         $db->stayOnMaster();
         $this->inviteJobseeker($user->id,array($jobseeker_id));
         $db->leaveOnMaster();
      }*/ 

      //checkout the uploaded resume's job_id,if not system,then update the job's persontest result
      if(!empty(JRequest::getInt('job_id',0))){
         PInterviewHelper::updatePersontestResult($jobseeker_id);
      }
      //after upload resume successfully,check this resume selected job,send system email
      if(!empty($selected_job_id)){
         if($type=='add'){
            $this->inviteJobseeker($user->id,array($jobseeker_id),true);
         }elseif($type=='edit' && ($selected_job_id != $origin_job_id)){
            $this->inviteJobseeker($user->id,array($jobseeker_id),true,'edit');
         }
      }
      //insert upload attchment
      $filename = basename(JRequest::getString('fileuploadname'));
      $filerealname = basename(JRequest::getString('filerealname'));
      try {
         // find out what the charset is 
         $charset = detectCharsetEncoding($filerealname);
         if($charset != false && $charset != 'UTF-8') {
            $filerealname = mb_convert_encoding($filerealname , 'UTF-8' ,  trim($charset));
         }
      }
      catch(Exception $e) {}

      $datadir = getUserDataDir($user->id);
      $extdir = getUserExtDir($user->id);
      $upload_path=OC::$SERVERROOT."/data".$datadir."/company/".$extdir."/resumes/";

      // final common upload path will be like: 
      // /aa/bb/cc/dd/<hashkey>/upload/100000/
      // 
      // the path is design to handle multiple companies uploading same resume but might be slightly different 
      // the resume_version. we append company id after source to different different company upload same resumes 
      $resume_storagepath = PStorage::getResumeStoragePath($storehash, true);
      $resume_storagepath .= "/".$resumeversion."/upload/".$user->id."/"; 

      if(!JFolder::create($resume_storagepath)){
         $db->leaveOnMaster();
         $this->setError('系统错误，请重试');
         return false;
      }
      
      $tables = array('*PREFIX*hr_jobseeker','*PREFIX*hr_jobseeker-'.$jobseeker_id);
      
      if($filename){
         $file_type=JFile::getExt($filename);
         $attachment=$jobseeker_id.'.'.$file_type;
         $session=PFactory::getSession();
         if(preg_match("/^".$session->getId()."/", $filename)){
            $dir = $upload_path.'upload/tmp/'.$filename;
            if(is_file($dir)) {
               $query='INSERT INTO *PREFIX*hr_jobseeker_uploaded ('.($jobseekerid ? 'modifier,modified,':'creator,created,').'jobseeker_id,company_id,upload_attachment)
                       VALUES ('.$db->quote(OC_User::getUser()).',UTC_TIMESTAMP(),'.intval($jobseeker_id).','.intval($user->id).','.$db->quote($filerealname).')
                       ON DUPLICATE KEY UPDATE upload_attachment = values(upload_attachment)'; 
               $db->setQuery(PUtil::replaceOCPrefix($query));
               if($db->execute()){
                  array_push($tables, '*PREFIX*hr_jobseeker_uploaded-'.$jobseeker_id);
                  
                  //delete preview's uploaded files...
                  $itr = new DirectoryIterator($resume_storagepath);
                  foreach ($itr as $file) {
                     if ($itr->isFile()) {
                        $pathName = $itr->getPathname();
                        if(strpos($pathName, 'resume.html') !== FALSE) continue;
                        if(strpos($pathName, 'resume.html.orig') !== FALSE) continue;
                        if (!JFile::delete($pathName)) {
                           $db->leaveOnMaster();
                           $this->setError('系统错误，请重试');
                           return false;
                        }
                     }
                  }
                  // handle content conversion 
                  $finfo= finfo_open(FILEINFO_MIME_TYPE);
                  $content_type = finfo_file($finfo, $dir);
                  finfo_close($finfo);

                  if ($content_type == 'text/plain' || $content_type == 'text/html') {
                     $content = file_get_contents($dir);
                     $mht = false; 
                     if(in_array($file_type, array('doc', 'docx', 'mht')) &&  stripos($content, 'MIME-version:') !== FALSE) {
                        // mht document 
                        $content_type = 'multipart/related'; 
                        $mht = true; 
                     }

                     if(!$mht) {
                        $charset = false;
                        if($content_type == 'text/html') {
                           // let do a quick search from charset 
                           preg_match('/charset=([\'"]?)([-a-z0-9_]+)\\1/i',$content,$charset);
                           if(!empty($charset)) $charset = strtoupper(end($charset)); 
                        }
                        if($charset != 'UTF-8') {
                           $charset = detectCharsetEncoding(null, $dir);
                           if($charset != false && $charset != 'UTF-8') {
                              try {
                                 $content = mb_convert_encoding($content , 'UTF-8' ,  $charset);
                              }
                              catch(Exception $e) { }
                           }
                        }

                        if($content_type == 'text/html') {
                           $content = preg_replace('/charset=([-a-z0-9_]+)/i','charset=utf-8', $content);
                           $content = preg_replace('/charset=[\'"]([-a-z0-9_]+)[\'"]/i','charset="utf-8"', $content);
                           $content = preg_replace('/<meta.*charset=([\'"]?)([-a-z0-9_]+)\\1.*?>/i', '<meta http-equiv="Content-type" content="text/html; charset=utf-8" />', $content);
                           $content = compactHtml(clear_xss2($content, array('form', 'meta')));
                        } else {
                           $content = strip_tags($content);
                        }

                        // write converted content back 
                        file_put_contents($dir, $content); 
                     }
                  }

                  // move the file to correct place
                  @rename($dir, $resume_storagepath.$attachment);
               }
               
               CacheHelper::triggerRemove($user->id, array('*PREFIX*hr_jobseeker_uploaded-'.$jobseeker_id));
            }
         }
      }else{
         $query='INSERT INTO *PREFIX*hr_jobseeker_uploaded('.($jobseekerid ? 'modifier,modified,':'creator,created,').'jobseeker_id,company_id)
                 VALUES ('.$db->quote(OC_User::getUser()).',UTC_TIMESTAMP(),'.($jobseekerid ? intval($jobseeker_id) : intval($jobseeker_id)).','.intval($user->id).')
                 ON DUPLICATE KEY UPDATE
                 modifier=values(modifier),
                 modified=values(modified)';      
         $db->setQuery(PUtil::replaceOCPrefix($query));
         $db->execute();
         CacheHelper::triggerRemove($user->id, array('*PREFIX*hr_jobseeker_uploaded-'.$jobseeker_id));
      }
      
      $new = true;
      $changed = false;
      $resumefile = $resume_storagepath.'resume.html';
      
      $fields = array(
               array('id' => 'ppp_name', 'name' => 'name'),
               array('id' => 'ppp_email', 'name' => 'email'),
               array('id' => 'ppp_phone', 'name' => 'phone')
      );
      
      // form now on we reset $post['email'] to empty if it's fake email address
      if(isFakeEmail($post['email'])) {
         $post['email'] = ''; 
      }

      // If only resume info changed, we don't touch attachment, and $new will be false.
      if (!empty($jobseekerinfo) && is_file($resumefile) && empty($filename)) {
         $htmDoc = '';
         libxml_use_internal_errors(true);
          
         foreach ($fields as $field) {
            if ($jobseekerinfo->$field['name'] != $post[$field['name']]) {
               $changed = true;
               if (empty($htmDoc)) {
                  $htmDoc = new DOMDocument;
                  $htmDoc->loadHTMLFile($resumefile);
               }
               $e = $htmDoc->getElementById($field['id']);
               if (empty($e)) {
                  $new = true;
                  break;
               }
               $e->nodeValue = $post[$field['name']];
               $new = false;
               //echoDbgLog($field['name'].' has changed');
            }
         }
          
         if (!empty($htmDoc) && !$new) {
            $htmDoc->saveHTMLFile($resumefile);
         }
         if (!$changed) {
            $new = false;
         }
         libxml_clear_errors();
      }
 
      if(!empty($filerealname)) {
         $post['attachment'] = array(
               'realname' => $filerealname,
               'link' => OC_Helper::linkTo('resumes','ajax/getattachment.php', array('resumeid' => $jobseeker_id))
         );
      }
      // re-create backup by default    
      $resumeTmp = new OCP\Template('resumes', 'resume.html', '');
      $resumeTmp->assign('userData', $post);
      $resumeHtml = compactHtml($resumeTmp->fetchPage());
      JFile::write($resumefile.".orig", $resumeHtml);
  
      // This case will force re-create the resume html and parse attachment.
      if ($new) {
         // create a new copy of resume file since data has been changed 
         JFile::write($resumefile, $resumeHtml);
         
         // parse attachment
         include_once(JPATH_SITE.'/components/com_jobmail/helpers/queue.php');
         try {
            $queue = new QueueHelper();

            $data = array();
            $data['resumefile'] = $resumefile; 

            $tubename = 'localattachmentTube'; 

            // need to check if global queue enabled. If not, everything should be in localhost beanstalkd
            $config = JFactory::getConfig();
            if($config->get('globalqueue')) {
               $task = array();
               $task['tube'] = $tubename;
               $task['data'] = $data; 
               $task['companyid'] = PFactory::getMasterUser()->id;
               $data = $task; 
               $tubename = 'globaltaskTube';
            }
 
            $queue->putTask($data, $tubename, 0);
         } catch(Exception $e) {}
         
         //echoDbgLog('re-create resume html file');
      }
     
     //update oc_calendar_interview_events, oc_calendar_interview_result
     $jobids=array();
     if($jobseekerid){
        if($jobseekerinfo->job_id!=$job_id){
           if($jobseekerinfo->job_id)
              array_push($jobids, $jobseekerinfo->job_id);
           if($job_id)
              array_push($jobids, $job_id);          
           $query="UPDATE *PREFIX*calendar_interview_events SET jobid=".intval($job_id)." WHERE jobseekerid=".intval($jobseekerid);
           $db->setQuery(PUtil::replaceOCPrefix($query));
           $db->execute();
           $query="UPDATE *PREFIX*calendar_interview_result SET jobid=".intval($job_id)." WHERE jobseekerid=".intval($jobseekerid);
           $db->setQuery(PUtil::replaceOCPrefix($query));
           $db->execute();
           array_push($tables, '*PREFIX*calendar_interview_events', '*PREFIX*calendar_interview_result');
        }    
     }else{
        //add new resume,recount jos_jobs_employer's num_jobseekers
        $query = "UPDATE #__jobs_employer AS je SET je.num_jobseekers=(SELECT COUNT(*) FROM  *PREFIX*hr_jobseeker AS j
                                                                       LEFT JOIN #__jobs_job AS jj ON jj.id=j.job_id
                                                                       WHERE j.is_trashed=0 AND jj.is_trashed=0 AND j.company_id=je.user_id)
                 WHERE je.user_id=" . $user->id;
        $db->setQuery(PUtil::replaceOCPrefix($query));
        $db->execute();
        array_push($tables, '#__jobs_employer');
        if($job_id)
           array_push($jobids, $job_id);
       }
       if(!empty($jobids)){
          $query="UPDATE #__jobs_job AS a
                  SET num_applied = (SELECT COUNT(*) FROM  *PREFIX*hr_jobseeker WHERE is_trashed=0 AND job_id=a.id)
                  WHERE a.id in (".implode(',', $jobids).') AND a.employer_id='.$user->id;
          $db->setQuery(PUtil::replaceOCPrefix($query));
          $db->execute();
          
          array_push($tables, '#__jobs_job');
          foreach ($jobids as $tmp_job) {
             array_push($tables, '#__jobs_job-'.intval($tmp_job));
          }
       }
       
      CacheHelper::triggerRemove($user->id, $tables);
      $db->leaveOnMaster();
      return $jobseeker_id;
   }
   
   public function uploadResumeAttachment(){
      $upload =array(
            'tmp_name' => null,
            'name' => null,
            'upload_name'=>null,
            'size' => null,
            'type' => null,
            'error' => ""
      );
      if(!PCompanyHelper::isJobManager()) {
         $upload['error']="您无权访问该资源";
         return json_encode($upload);
      }
      $session = PFactory::getSession();
      $session_id = $session->getId();     
      $app = PFactory::getApplication();
      $user = PFactory::getMasterUser();

      $datadir = getUserDataDir($user->id);
      $extdir = getUserExtDir($user->id);
      $upload_path=OC::$SERVERROOT."/data".$datadir."/company/".$extdir."/resumes/";

      $post = JRequest::get('post');
      if(empty($_FILES['Filedata'])) {
         return jsonError("没有上传数据", null, false);
      }
      $upload = array_merge($upload, $_FILES['Filedata']);
      //Check for security token
      if(!PSession::checkToken()) {
         $upload['error'] = '登录已失效，请重新登录';
         return json_encode($upload);
      }
      //UPLOAD FILE
      $allowTypes = array("application/msword",
                   "application/vnd.ms-office",
                   "application/kswps",
                   "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                   "application/pdf",
                   "application/vnd.oasis.opendocument.text",
                   "application/x-mht",
                   "text/html",
                   "multipart/related",
                   "message/rfc822", 
                   "text/plain"
                   );
      $file_max_size=2*1024*1024;
      $target_path = JPath::clean($upload_path.'upload/tmp/');
      if(!JFolder::exists($target_path)){
         JFolder::create($target_path);
      }           
      $filedata = $_FILES['Filedata'];
      if(empty($filedata['tmp_name'])) {
         $upload['error'] = '文件太大'; 
         return json_encode($upload);
      }
      $origin_name=$filedata['name'];
      $fileext = JFile::getExt($filedata['name']);
      $filedata['name'] = $session_id.'_'.time().".".$fileext;
      $handle = new Upload($filedata, 'zh_CN');
      if(!$handle) {
         $upload['error'] = $handle->error;
         return json_encode($upload);
      }
      $handle->allowed = $allowTypes;
      $handle->file_max_size=$file_max_size;
      $handle->file_overwrite=true;
      $handle->no_script=false;
      $handle->process($target_path);
      if(!$handle->processed) {
         $upload['error']=$handle->error;
         return json_encode($upload);
      }else{ 
         //if have upload successfully before,delete preview's upload attachment
         $filename = JRequest::getString('filename');
         if($filename){
            $filename=basename($filename);
            if(preg_match("/^".$session_id."/", $filename) && JFile::exists($target_path.$filename)){
               JFile::delete($target_path.$filename);
            }
         }
      }
      $upload['upload_name']=$filedata['name'];     
      return json_encode($upload);    
   }
   
   public function getCompanyUploadJobId() {
      $user=PFactory::getMasterUser();
      $subUser = PCompanyHelper::getSubUser();
      $adminAllUsers = PCompanyHelper::getJobAdminAllUser();
      $db = PFactory::getDbo();
      $query = "SELECT id FROM #__jobs_job WHERE employer_id=". intval(PFactory::getMasterUser()->id) . " AND system=1";
      $db->setQuery($query);
      $jobid = $db->loadResult();
      if(!$jobid) {
         // hidden upload job id doesn't exist, create one automatically
         $query='INSERT INTO #__jobs_job(job_title,employer_id,source,system)
              VALUES("无职位",'.intval(PFactory::getMasterUser()->id).',"pipapai",1)';
         $db->setQuery($query);
         if(!$db->execute()) {
            return false;
         }
         $query='SELECT LAST_INSERT_ID()';
         $db->setQuery($db->useLastConnection($query));
         $jobid=$db->loadResult();
         if (!empty($adminAllUsers)) {
            foreach ($adminAllUsers as $adminAllUser) {
               $values[] = "(" . intval($jobid) . ", " . $db->quote($adminAllUser->uid) . ")";
            }
         }        
         CacheHelper::triggerRemove($user->id, array('#__jobs_job'));
      }
      if(!empty($subUser->uid)){
         $subModel = new PCompanyModelSubAccounts();
         $permissions = $subModel->getUserPermissions($subUser->uid);
         if(!($permissions & PERMISSION_JOB_ADMIN_ALL)) {
            $values[] = "(" . intval($jobid) . ", " . $db->quote($subUser->uid) . ")";
         }
         // if subuser doesn't have assiged permission, just give it
         $permChanged = false;
         if(!($permissions & PERMISSION_JOB_ADMIN_ALL || $permissions & PERMISSION_JOB_ADMIN_ASSIGNED)) {
            $permissions |= PERMISSION_JOB_ADMIN_ASSIGNED;
            if(!$subModel->setUserPermissions($subUser->uid, $permissions)) {
               $this->setError('系统错误');
               return false;
            }
            $permChanged = true;
         }
         if($permChanged) {
            CacheHelper::triggerRemove($subUser->uid, array('*PREFIX*hr_jobmanager'));
         }
         if(!empty($values)) {
            $query = "INSERT IGNORE INTO *PREFIX*hr_jobmanager (jobid, manager) VALUES " . implode(",", $values);
            $db->setQuery(PUtil::replaceOCPrefix($query));
            if (!$db->execute())
               return false;
            // Event Driven Cache/Object Caching - clear any cache related to affected tables
            CacheHelper::triggerRemove($user->id, array('*PREFIX*hr_jobmanager'));
            if(!PFactory::isMasterUser())
               CacheHelper::triggerRemove(OC_User::getUser(), array('*PREFIX*hr_jobmanager'));
         }
         
      }
      
      return $jobid;
   }
   
   private function isRarOrZip($file) {
      // get the first 7 bytes
      $bytes = file_get_contents($file, FALSE, NULL, 0, 7);
      $ext = strtolower(substr($file, - 4));

      // RAR magic number: Rar!\x1A\x07\x00
      // http://en.wikipedia.org/wiki/RAR
      if ($ext == '.rar' and bin2hex($bytes) == '526172211a0700') {
         return TRUE;
      }

      // ZIP magic number: none, though PK\003\004, PK\005\006 (empty archive), 
      // or PK\007\008 (spanned archive) are common.
      // http://en.wikipedia.org/wiki/ZIP_(file_format)
      if ($ext == '.zip' and substr($bytes, 0, 2) == 'PK') {
         return TRUE;
      }

      return FALSE;
   }

   public function batchupload(){
      $upload =array(
            'tmp_name' => null,
            'name' => null,
            'upload_name'=>null,
            'size' => null,
            'type' => null,
            'error' => ""
      );
      if(!PCompanyHelper::isJobManager()) {
         $upload['error']="您无权访问该资源";
         return json_encode($upload);
      }
      $session = PFactory::getSession();
      $session_id = $session->getId();     
      $app = PFactory::getApplication();
      $user = PFactory::getMasterUser();
      $datadir = getUserDataDir($user->id);
      $extdir = getUserExtDir($user->id);
      $upload_path=OC::$SERVERROOT."/data".$datadir."/company/".$extdir."/resumes/";
      $post = JRequest::get('post');
      if(empty($_FILES['Filedata'])) {
         return jsonError("文件太大", null, false);
      }
      $upload = array_merge($upload, $_FILES['Filedata']);
      //Check for security token
      if(!PSession::checkToken()) {
         $upload['error'] = '登录已失效，请重新登录';
         return json_encode($upload);
      }
      //UPLOAD FILE
      $allowTypes = array("application/msword",
                   "application/vnd.ms-office",
                   "application/kswps",
                   "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                   "application/pdf",
                   "application/vnd.oasis.opendocument.text",
                   "application/x-mht",
                   "text/html",
                   "multipart/related",
                   "message/rfc822", 
                   "text/plain",
                   "application/zip",
//                   "multipart/x-zip",
//                   "application/rar",
//                   "application/x-rar-compressed",
                   "application/octet-stream"
                   );
      $file_max_size=10*1024*1024;
      $target_path = JPath::clean($upload_path.'upload/tmp/');
      if(!JFolder::exists($target_path)){
         JFolder::create($target_path);
      }           
      $filedata = $_FILES['Filedata'];
      $origin_name=$filedata['name'];
      $fileext = JFile::getExt($filedata['name']);
      $filedata['name'] = $session_id.'_'.time().".".$fileext;
      $handle = new Upload($filedata, 'zh_CN');

      if(($handle->file_src_mime == 'text/html' || $handle->file_src_mime == 'text/plain') && ($fileext == 'doc' || $fileext == 'docx' )){
         $handle->file_src_mime = 'application/msword';
         $handle->file_src_name_ext = $fileext;  
      }

      if(!$handle) {
         $upload['error'] = $handle->error;
         return json_encode($upload);
      }
      $handle->allowed = $allowTypes;
      $handle->file_max_size=$file_max_size;
      $handle->file_overwrite=true;
      $handle->no_script=false;
      $handle->process($target_path);
      if(!$handle->processed) {
         $upload['error']=$handle->error;
         return json_encode($upload);
      }

      // the upload is good so far, let check the file types 

      $destfile = $handle->file_dst_pathname; 
      
      // handle content conversion 
      $finfo= finfo_open(FILEINFO_MIME_TYPE);
      $content_type = finfo_file($finfo, $destfile);
      finfo_close($finfo);

      if($content_type == 'application/octet-stream' && !$this->isRarOrZip($destfile)) {
         $upload['error'] = '不正确的文件格式。';
         return json_encode($upload);
      } 
      
      // we don't need to check html security issue as user will not be able to open it 
      // the backend script will clear it up 

      try {
         $charset = detectCharsetEncoding(null, $origin_name);
         if($charset != false && $charset != 'UTF-8') {
            $origin_name = mb_convert_encoding($origin_name, 'UTF-8', $charset);
         }
      } catch(Exception $e) {}

      // add to delay task 
      $status = DelayTaskJob::add(
            array('summary'=>'导入简历:'.strmaxwordlen(preg_replace('/\s+/', '', $origin_name), 7), 
                  'userid'=>PFactory::getMasterUser()->get('id'),
                  'owner'=>OC_User::getUser(),
                  'handler'=>'/usr/bin/php ' . realpath(JPATH_SITE . '/../cloud/cli/resumebatchupload.php'),
                  'parameters'=>json_encode(array($destfile)),
                  'exclusive'=> false,  // support multiple upload concurrently 
                  'duplicate'=> false,  // don't support duplicate task per-user 
                  'priority'=>9
                 )
            );

      $upload['upload_name'] = $filedata['name'];     
      return json_encode($upload);    
   }

}
